package com.qq.mobilemanager.activity;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.IPackageDataObserver;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.PackageStats;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RemoteException;
import android.os.SystemClock;
import android.text.format.Formatter;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.qq.mobilesafe.R;
import com.qq.mobilesafe.base.adapter.ViewHolder;
import com.qq.mobilesafe.base.adapter.abslistview.CommonAdapter;
import com.qq.mobilesafe.domain.CacheInfo;

public class CleanCacheActivity extends Activity implements OnClickListener {

	private PackageManager packageManager;

	private List<CacheInfo> cacheList;

	// private CacheAdapter adapter ;

	@ViewInject(R.id.list_view)
	private ListView listView;

	@ViewInject(R.id.pb)
	private ProgressBar pb;

	@ViewInject(R.id.tv_appname)
	private TextView tv_appname;

	@ViewInject(R.id.tv_cachesize)
	private TextView tv_cachesize;

	@ViewInject(R.id.tv_cache_count)
	private TextView tv_result;

	@ViewInject(R.id.iv_icon)
	private ImageView iv_icon;

	@ViewInject(R.id.scan_line)
	private ImageView iv_scan_line;

	@ViewInject(R.id.btn_cleanAll)
	private Button btn_cleanAll;

	@ViewInject(R.id.bt_scan)
	private Button btn_scan;

	@ViewInject(R.id.rl_content)
	private RelativeLayout rl_content;

	@ViewInject(R.id.rl_result)
	private RelativeLayout rl_result;

	private ScanTask task;

	private int cache_count = 0;

	private int tv_cache_size = 0;

	@ViewInject(R.id.ib_delete)
	private ImageButton ib_delete;

	// private int progress ;
	IPackageStatsObserver.Stub mStatsObserver = new IPackageStatsObserver.Stub() {

		@Override
		public void onGetStatsCompleted(PackageStats pStats, boolean succeeded)
				throws RemoteException {

			try {
				CacheInfo info = new CacheInfo();
				long cacheSize = pStats.cacheSize;
				String packageName = pStats.packageName;

				PackageInfo packageInfo = packageManager.getPackageInfo(
						packageName, 0);

				Drawable icon = packageInfo.applicationInfo
						.loadIcon(packageManager);
				String appName = packageInfo.applicationInfo.loadLabel(
						packageManager).toString();

				info.appName = appName;
				info.icon = icon;
				info.appPackageName = packageName;

				if (cacheSize > 0) {
					cache_count++;
					tv_cache_size += cacheSize;
					info.cacheSize = cacheSize;
					cacheList.add(0, info);
				} else {
					cacheList.add(info);
				}
				task.updateCacheInfo(info);

			} catch (NameNotFoundException e) {
				e.printStackTrace();
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		packageManager = getPackageManager();

		initView();
		initData();

		// cacheList = new ArrayList<CacheInfo>();

		// public abstract void getPackageSizeInfo(String
		// packageName,IPackageStatsObserver observer);
		// packageManager.getPackageSizeInfo();
		// new Thread() {
		// public void run() {
		// List<PackageInfo> installedPackages = packageManager
		// .getInstalledPackages(0);
		//
		// for (PackageInfo packageInfo : installedPackages) {
		// getCacheSize(packageInfo);
		// }
		// handler.sendEmptyMessage(0);
		// };
		// }.start();
	}

	private void initView() {
		setContentView(R.layout.activity_clean_cache);
		ViewUtils.inject(this);

		btn_scan.setOnClickListener(this);
		btn_cleanAll.setOnClickListener(this);

	}

	private void initData() {
		task = new ScanTask();
		task.execute();
	}

	@Override
	protected void onPause() {
		super.onPause();

		if (task != null) {
			task.stop();
			task = null;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bt_scan:
			initData();
			rl_result.setVisibility(View.INVISIBLE);
			rl_content.setVisibility(View.VISIBLE);
			break;
		case R.id.btn_cleanAll:
			Method method;
			try {
				method = packageManager.getClass().getDeclaredMethod(
						"freeStorageAndNotify", long.class,
						IPackageDataObserver.class);
				method.setAccessible(true);
				method.invoke(packageManager, Long.MAX_VALUE, mDataObserver);
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		}
	}

	/**
	 * 一键清理
	 */
	IPackageDataObserver.Stub mDataObserver = new IPackageDataObserver.Stub() {
		@Override
		public void onRemoveCompleted(String packageName, boolean succeeded)
				throws RemoteException {
			Toast.makeText(CleanCacheActivity.this, "清理完毕", 0).show();
		}
	};

//	public void cleanAll(View view) {
//		// Method[] methods = PackageManager.class.getMethods();
//		// for (Method method : methods) {
//		// if (method.getName().equals("freeStorageAndNotify")) {
//		// try {
//		// method.invoke(packageManager, Integer.MAX_VALUE,
//		// mDataObserver);
//		// initData();
//		// } catch (Exception e) {
//		// e.printStackTrace();
//		// }
//		// }
//		// }
//		try {
//			Method method = PackageManager.class.getDeclaredMethod(
//					"freeStorageAndNotify", long.class,
//					IPackageDataObserver.class);
//			method.invoke(packageManager, Long.MAX_VALUE, mDataObserver);
//			// initData();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}

	// private void getCacheSize(PackageInfo packageInfo) {
	// try {
	// Method method = PackageManager.class.getDeclaredMethod(
	// "getPackageSizeInfo", String.class,
	// IPackageStatsObserver.class);
	// /**
	// * 第一个参数：调用该方法的对象 第二个参数：包名 第三个参数：IPackageStatsObserver实现类的对象
	// */
	// method.invoke(packageManager,
	// packageInfo.applicationInfo.packageName, mStatsObserver);
	//
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	//
	// }

	private class CacheAdapter extends CommonAdapter<CacheInfo> {

		

		public CacheAdapter(Context context, int layoutId, List<CacheInfo> datas) {
		super(context, layoutId, datas);
	}

		@Override
		public void convert(ViewHolder holder, final CacheInfo cacheInfo) {
			holder.setText(R.id.tv_name, cacheInfo.appName);
			holder.setText(
					R.id.tv_cache_size,
					"缓存大小:"
							+ Formatter.formatFileSize(CleanCacheActivity.this,
									cacheInfo.cacheSize));
			holder.setImageDrawable(R.id.iv_icon, cacheInfo.icon);

			holder.setVisible(R.id.ib_delete, cacheInfo.cacheSize > 0 ? true
					: false);

			holder.setOnClickListener(R.id.ib_delete, new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent();
					// <intent-filter>
					// <action
					// android:name="android.settings.APPLICATION_DETAILS_SETTINGS"
					// />
					// <category android:name="android.intent.category.DEFAULT"
					// />
					// <data android:scheme="package" />
					// </intent-filter>
					intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
					intent.addCategory("android.intent.category.DEFAULT");
					intent.setData(Uri.parse("package:"
							+ cacheInfo.appPackageName));
					startActivity(intent);
				}
			});
		}

	}

	private class ScanTask extends AsyncTask<Void, CacheInfo, String> {

		private CacheAdapter adapter;

		private int progress;

		boolean isFinish = false;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// 第一个参数：相对父亲
			TranslateAnimation translateAnimation = new TranslateAnimation(
					Animation.RELATIVE_TO_PARENT, 0,
					Animation.RELATIVE_TO_PARENT, 0,
					Animation.RELATIVE_TO_PARENT, 0f,
					Animation.RELATIVE_TO_PARENT, 0.8f);
			translateAnimation.setDuration(800);
			translateAnimation.setRepeatCount(Animation.INFINITE);
			translateAnimation.setRepeatMode(Animation.REVERSE);
			iv_scan_line.startAnimation(translateAnimation);
		}

		@Override
		protected String doInBackground(Void... params) {

			List<PackageInfo> installedPackages = packageManager
					.getInstalledPackages(0);

			pb.setMax(installedPackages.size());

			progress = 0;

			cacheList = new ArrayList<CacheInfo>();

			for (PackageInfo packageInfo : installedPackages) {
				progress++;
				String packageName = packageInfo.packageName;
				// Drawable icon =
				// packageInfo.applicationInfo.loadIcon(packageManager);
				// String appName =
				// packageInfo.applicationInfo.loadLabel(packageManager).toString();

				try {
					Method method = PackageManager.class.getDeclaredMethod(
							"getPackageSizeInfo", String.class,
							IPackageStatsObserver.class);
					// 第一个参数：调用该方法的对象 第二个参数：包名 第三个参数：IPackageStatsObserver实现类的对象
					method.invoke(packageManager, packageName, mStatsObserver);
					SystemClock.sleep(200);
					if (isFinish) {
						break;
					}

				} catch (Exception e) {
					e.printStackTrace();
				}

			}

			return null;
		}

		public void updateCacheInfo(CacheInfo info) {
			publishProgress(info);
		}

		public void stop() {

			isFinish = true;

		}

		@Override
		protected void onProgressUpdate(CacheInfo... values) {
			super.onProgressUpdate(values);

			CacheInfo info = values[0];
			if (isFinish) {
				return;
			}

			iv_icon.setImageDrawable(info.icon);
			tv_appname.setText(info.appName);
			tv_cachesize.setText("缓存大小："
					+ Formatter.formatFileSize(getApplicationContext(),
							info.cacheSize));
			pb.setProgress(progress);

			if (adapter == null) {
				adapter = new CacheAdapter(CleanCacheActivity.this, R.layout.item_clean_cache,cacheList);
				listView.setAdapter(adapter);
			} else {
				adapter.notifyDataSetChanged();
			}
			listView.smoothScrollToPosition(adapter.getCount());

		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);

			if (isFinish) {
				return;
			}
			Collections.sort(cacheList);
			listView.smoothScrollToPosition(0);// 滚动到第0个位置
			rl_result.setVisibility(View.VISIBLE);
			rl_content.setVisibility(View.INVISIBLE);
			tv_result.setText("总共有"+ cache_count+ "个缓存文件,缓存大小"
					+ Formatter.formatFileSize(getApplicationContext(),tv_cache_size));
		}
	}

}
